import {defineStore} from 'pinia'
import {ref} from "vue"
import store from "@/store"
import {usePermissionStore} from "./permission"
import {useTagsViewStore} from "./tags-view"
import {getToken, removeToken, setToken} from "@/utils/cache/cookies"
import router, {resetRouter} from "@/router"
import {type RouteRecordRaw} from "vue-router"
import asyncRouteSettings from "@/config/async-route"
import {getToken as getUserToken,} from '@/api/login'
import {setToken as saveUserToken, getToken as getUserTokenLocal} from '@/utils/cache/user'
import {getUserInfoByToken} from '@/api/user'
import {User} from "@/types/user";


export const useCounterStore = defineStore('counter', {
  state: () => {
    return {count: 0}
  },
  actions: {
    increment() {
      this.count++
    },
  },
})


export const useUserStore = defineStore("user", () => {
  const token = ref<string>(getUserTokenLocal() || "")
  const roles = ref<string[]>([])
  const username = ref<string>("")
  const userInfo = reactive<User>({})
  const permissionStore = usePermissionStore()
  const tagsViewStore = useTagsViewStore()

  /** 设置角色数组 */
  const setRoles = (value: string[]) => {
    roles.value = value
  }
  /** 登录 */
  const login = (name: string, pass: string) => {
    return new Promise((resolve, reject) => {
      // login
     
      getUserToken(name, pass).then(res => {
        saveUserToken(res.response)

        getUserInfoByToken(res.response).then(r => {
          Object.assign(userInfo, r.response)
          console.log('res',r.response)
          resolve(r.response)
          alert('登录成功')
        })


      }).catch(error => {
        alert(error)
        reject(error)
      })
    })
  }
  /** 获取用户详情 */
  const getInfo = () => {
    return new Promise((resolve, reject) => {
      // detail
    })
  }
  /** 切换角色 */
  const changeRoles = async (role: string) => {
    const newToken = "token-" + role
    token.value = newToken
    setToken(newToken)
    // 获取用户信息
    await getInfo()
    // 重新获取权限
    _resetTagsView()
  }
  /** 登出 */
  const logout = () => {
    removeToken()
    token.value = ""
    roles.value = []
    resetRouter()
    _resetTagsView()
  }
  /** 重置 Token */
  const resetToken = () => {
    removeToken()
    token.value = ""
    roles.value = []
  }
  /** 重置 visited views 和 cached views */
  const _resetTagsView = () => {
    tagsViewStore.delAllVisitedViews()
    tagsViewStore.delAllCachedViews()
  }

  return {token, roles, username, setRoles, login, getInfo, changeRoles, logout, resetToken}
})

/** 在 setup 外使用 */
export function useUserStoreHook() {
  return useUserStore(store)
}
